﻿using cap01.Common;
using cap01.Common.Redis;
using Microsoft.AspNetCore.Http;

namespace cap01.Core.Session;

public class AuthSession
{
    static readonly CacheRepo<string> _repo = new("session");
    const string _tokenKey = "huasky_session_auth";

    /// <summary>
    /// 创建会话
    /// </summary>
    public static void Create(TokenData token)
    {
        _repo.Set(token.StaffId.ToString(), token.StaffId.ToString(), TimeSpan.FromSeconds(AppConfig.Settings.ExpireSecond));
    }

    public static SessionData GetSessionData(HttpRequest request)
    {
        var val = string.Empty;
        var cookie = request.Cookies;
        if (cookie.ContainsKey(_tokenKey))
        {
            val = cookie[_tokenKey];
        }
        else
        {
            var headers = request.Headers;
            if (headers.ContainsKey(_tokenKey))
            {
                val = headers[_tokenKey];
            }
        }
        if (string.IsNullOrEmpty(val)) return SessionData.NotLogin;

        var token = TokenData.Parse(val);

        var session = _repo.GetOrDefault(token.StaffId.ToString());

        if (session == null) //超时了
            return SessionData.Expired;

        return SessionData.Normal(token);
    }


}